﻿using System;
using System.Linq;
using System.Threading;
using System.Web.Mvc;
using System.Web.Routing;
using Tradukisto.Engine.DataAnnotations;
using Tradukisto.Engine.ResourceProviders;

namespace Tradukisto.Engine.Utilities
{
    public static class LocalizationConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            //routes.MapRoute(
            //    "Account", 
            //    "Account/{action}", 
            //    new { controller = "Account", action = "Index" } 
            //);

            routes.MapRoute(
                LocalizationConstants.ROUTE_NAME, // Route name
                string.Format("{{{0}}}/{{controller}}/{{action}}/{{id}}", LocalizationConstants.ROUTE_PARAMNAME_LANG), // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );
        }

        public static void RegisterResourceProvider(Func<ILocalizationProvider> initializer)
        {
            LocalizationProvider.RegisterResourceProvider(initializer);
            LocalizationProvider.RegisterCultureNameResolver(() => Thread.CurrentThread.CurrentUICulture.Name);
        }

        public static void RegisterResourceProvider(Func<ILocalizationProvider> initializer, Func<string> cultureNameResolver)
        {
            LocalizationProvider.RegisterResourceProvider(initializer);
            LocalizationProvider.RegisterCultureNameResolver(cultureNameResolver);
        }

        public static void RegisterModelProviders()
        {
            // register the model metadata provider
            ModelMetadataProviders.Current = new LocalizableModelMetadataProvider();

            // register the model validation provider
            var provider = ModelValidatorProviders.Providers.Where(p => p.GetType() == typeof(DataAnnotationsModelValidatorProvider)).FirstOrDefault();
            if (provider != null)
            {
                ModelValidatorProviders.Providers.Remove(provider);
            }
            provider = new LocalizableModelValidatorProvider();
            ModelValidatorProviders.Providers.Add(provider);
        }
    }
}

